namespace Warehouse

open System.Windows.Data
open System
open System.Windows.Controls
open System.Windows
open FSharp.Windows
open Warehouse.Controls

type PurchaseOrderDetailsEvents = 
    | Save of (unit -> unit)
    | BulkInput 
    | AddLineItem 
    | NewProductForInvalidUPC
    | AddInvalidUPCToExistingProduct

type PurchaseOrderDetailsView() as this = 
    inherit View<PurchaseOrderDetailsEvents, PurchaseOrderDetailsModel, PurchaseOrderDetailsWindow>()

    let vendor = this.Control.Vendor

    do
        vendor.DisplayMemberPath <- "CompanyName"
        this.Control.Note.MaxLength <- 100
        this.CancelButton <- this.Control.Cancel
        this.Control.Override.EnsureDecimal()
        this.Control.Commission.EnsurePositiveDecimal()
        this.Control.Shipping.EnsurePositiveDecimal()

    override this.EventStreams = 
        [
            this.Control.Save, Save this.OK
            this.Control.BulkInput, BulkInput
            this.Control.Add, AddLineItem
            this.Control.NewProduct, NewProductForInvalidUPC
            this.Control.ExistingProduct, AddInvalidUPCToExistingProduct
        ] 
        |> List.ofButtonClicks

    override this.SetBindings model = 

        Binding.FromExpression 
            <@
                vendor.ItemsSource <- model.AllVendorsList
                vendor.SelectedItem <- model.Vendor

                this.Control.Note.Text <- model.Note
                this.Control.Override.Text <- string model.Override

                this.Control.LineItems.SelectedItem <- model.SelectedLineItem

                this.Control.OverridePercentage.IsChecked <- Nullable model.OverridePercentage
                this.Control.OverrideTotalAmount.IsChecked <- Nullable model.OverrideTotalAmount
                this.Control.Override.IsEnabled <- model.IsOverrideEnabled

                this.Control.Commission.Text <- string model.Commission
                this.Control.Commission.IsEnabled <- model.OverrideTotalAmount
                this.Control.Shipping.Text <- string model.Shipping
                this.Control.Shipping.IsEnabled <- model.OverrideTotalAmount
            @>        

        Binding.FromExpression(
            <@
                this.Control.NewProduct.IsEnabled <- isNull model.SelectedLineItem.UPC.Product
                this.Control.ExistingProduct.IsEnabled <- isNull model.SelectedLineItem.UPC.Product
            @>,
            fallbackValue = false
        )         

        Binding.TwoWay
            <@ 
                this.Control.Date.Text <- string model.Date 
            @>

        this.Control.LineItems.SetBindings(
            model,
            itemsSource = <@ model.LineItems @>,
            columnBindings = fun item ->
                [
                    this.Control.UPC, <@@ item.UPCode @@>
                    this.Control.Quantity, <@@ item.Quantity @@>
                ]
        )
